package com.hziee.graduate.ticket.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hziee.graduate.ticket.dao.CouponOrderDao;
import com.hziee.graduate.ticket.dto.R;
import com.hziee.graduate.ticket.entity.Coupon;
import com.hziee.graduate.ticket.entity.CouponOrder;
import com.hziee.graduate.ticket.service.CouponOrderService;
import com.hziee.graduate.ticket.service.CouponService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service("couponOrderService")
public class CouponOrderServiceImpl extends ServiceImpl<CouponOrderDao, CouponOrder> implements CouponOrderService {

    @Resource
    private CouponService couponService;

    @Override
    public R<Object> getACoupon(Long couponId, Long userId) {
        //1．查询优惠券
        Coupon coupon = couponService.getById(couponId);
       //2．判断秒杀是否开始
        if (coupon.getBeginTime().isAfter(LocalDateTime.now())) {
            //尚未开始
            return R.error("秒杀尚未开始");
        }
       // 3．判断秒杀是否已经结束
        if (coupon.getEndTime().isBefore(LocalDateTime.now())) {
            //尚未开始
            return R.error("秒杀已经结束");
        }
       //4．判断库存是否充足
        if (coupon.getCouponStock() < 1) {
            return R.error("库存不足");
        }
        synchronized (userId.toString().intern()) {
            CouponOrderService proxy = (CouponOrderService) AopContext.currentProxy();
            return proxy.createCouponOrder(couponId, userId);
        }

    }

    @Transactional
    public R<Object> createCouponOrder(Long couponId, Long userId) {
        //5.一人一单
        Integer count = query().eq("user_id", userId).eq("coupon_id", couponId).count();
        if(count > 0) {
            return R.error("用户已经抢过一次了");
        }
        //6．扣减库存
        boolean success = couponService.update()
                .setSql("coupon_stock = coupon_stock - 1")
                .eq("coupon_id", couponId)
                .gt("coupon_stock",0)
                .update();
        if (!success) {
            //扣减失败
            return R.error("库存不足");
        }
        //7．创建订单
        CouponOrder couponOrder = new CouponOrder();
        couponOrder.setUserId(userId);
        couponOrder.setUserId(userId);
        couponOrder.setCouponId(couponId);
        couponOrder.setCreateTime(LocalDateTime.now());
        boolean save = save(couponOrder);
        //8．返回结果
        return R.success();
    }
}

